package cn.kgc.tangcco.service.impl;

import cn.kgc.tangcco.pojo.Idiom;
import cn.kgc.tangcco.service.IdiomService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestOperations;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author 李昊哲
 * @Description
 * @create 2021/2/4 17:17
 */
@Service
public class IdiomServiceImpl implements IdiomService {
    private final RestOperations restTemplate;
    private static ObjectMapper objectMapper = new ObjectMapper();

    public IdiomServiceImpl(RestOperations restTemplate) {
        this.restTemplate = restTemplate;
    }

    @HystrixCommand
    @Override
    public List<Idiom> findByIds(List<Integer> ids) throws JsonProcessingException {
        HttpHeaders headers = new HttpHeaders();
        //  请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> requestEntity = new HttpEntity<>(objectMapper.writeValueAsString(ids), headers);
        String url = "http://idiom-provider/idiom/findByIds";
        //  执行HTTP请求
        ResponseEntity<Idiom[]> responseEntity = restTemplate.postForEntity(url, requestEntity, Idiom[].class);
        Idiom[] idioms = responseEntity.getBody();
        List<Idiom> idiomList = Arrays.asList(idioms);
        //  输出结果
        return idiomList;
    }

    @HystrixCollapser(batchMethod = "findByIds", scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL, collapserProperties = {
            @HystrixProperty(name = "timerDelayInMilliseconds", value = "1000"),
            @HystrixProperty(name = "maxRequestsInBatch", value = "3"),
    })
    public Future<Idiom> selectById(Integer id) {
        return null;
    }
}
